package com.xteam.xnetworkdisk.utils;


import java.awt.*;
import java.awt.image.BufferedImage;;
import java.util.Random;

// 图片验证码类
public class ImageCaptchaUtil {

    private static final int WIDTH = 200;
    private static final int HEIGHT = 50;

    // 字符集
    private static final String CHAR_SET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

    public static BufferedImage generateCaptchaImage(String captchaCode) {
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2d = bufferedImage.createGraphics();

        // 设置随机背景色
        Color[] bgColors = {Color.WHITE, Color.LIGHT_GRAY, Color.YELLOW, Color.CYAN, Color.PINK};
        g2d.setColor(bgColors[new Random().nextInt(bgColors.length)]);
        g2d.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制干扰线
        //g2d.setColor(Color.);
        Random random = new Random();
        for (int i = 0; i < 5; i++) {
            int x1 = random.nextInt(WIDTH);
            int y1 = random.nextInt(HEIGHT);
            int x2 = random.nextInt(WIDTH);
            int y2 = random.nextInt(HEIGHT);
            g2d.drawLine(x1, y1, x2, y2);
        }

        // 绘制验证码字符
        Font[] fonts = {new Font("Arial", Font.BOLD, 40), new Font("Verdana", Font.PLAIN, 35), new Font("Times New Roman", Font.ITALIC, 45)};
        Color[] fontColors = {Color.BLACK, Color.RED, Color.BLUE, Color.GREEN, Color.MAGENTA};

        for (int i = 0; i < captchaCode.length(); i++) {
            g2d.setFont(fonts[new Random().nextInt(fonts.length)]);
            g2d.setColor(fontColors[new Random().nextInt(fontColors.length)]);
            g2d.drawString(String.valueOf(captchaCode.charAt(i)), 30 + i * 30, 35 + random.nextInt(10));
        }

        // 释放图形上下文
        g2d.dispose();

        return bufferedImage;
    }

    public static String generateRandomCode(int length) {
        Random random = new Random();
        StringBuilder code = new StringBuilder(length);
        for (int i = 0; i < length; i++) {
            int index = random.nextInt(CHAR_SET.length());
            code.append(CHAR_SET.charAt(index));
        }
        return code.toString();
    }
}
